package com.example.ercmssystem2.controller;

import com.example.ercmssystem2.entity.User;
import com.example.ercmssystem2.entity.Department;
import com.example.ercmssystem2.service.UserService;
import com.example.ercmssystem2.service.DepartmentService;
import com.example.ercmssystem2.util.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/users")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private DepartmentService departmentService;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private JwtUtil jwtUtil;

    // 从JWT token中获取当前用户
    private User getCurrentUserFromJwt(@RequestHeader(value = "Authorization", required = false) String authHeader) {
        if (authHeader == null || !authHeader.startsWith("Bearer ")) {
            return null;
        }
        
        try {
            String token = authHeader.substring(7);
            if (jwtUtil.validateToken(token)) {
                String username = jwtUtil.extractUsername(token);
                return userService.findByUsername(username);
            }
        } catch (Exception e) {
            // Token无效或解析失败
        }
        
        return null;
    }

    @GetMapping
    public ResponseEntity<?> getAllUsers(@RequestHeader(value = "Authorization", required = false) String authHeader) {
        User current = getCurrentUserFromJwt(authHeader);
        if (current == null) {
            return ResponseEntity.status(401).body(Map.of("success", false, "message", "未登录"));
        }
        
        if (!hasUserManagementAccess(current)) {
            return ResponseEntity.status(403).body(Map.of("success", false, "message", "无权限访问"));
        }

        List<User> users;
        if (isAdmin(current)) {
            users = userService.findAllUsers();
        } else if (isDeptManager(current)) {
            List<Long> deptIds = departmentService.getUserManageableDepartments(current.getId())
                    .stream().map(Department::getId).toList();
            users = userService.findByDepartmentIds(deptIds);
        } else {
            return ResponseEntity.status(403).body(Map.of("success", false, "message", "无权限访问"));
        }

        Map<String, Object> response = new HashMap<>();
        response.put("success", true);
        response.put("data", users);
        return ResponseEntity.ok(response);
    }

    @GetMapping("/current")
    public ResponseEntity<User> getCurrentUser(@RequestHeader(value = "Authorization", required = false) String authHeader) {
        User currentUser = getCurrentUserFromJwt(authHeader);
        if (currentUser != null) {
            return ResponseEntity.ok(currentUser);
        } else {
            return ResponseEntity.notFound().build();
        }
    }

    @GetMapping("/{id}")
    public ResponseEntity<?> getUserById(@PathVariable Long id,
                                       @RequestHeader(value = "Authorization", required = false) String authHeader) {
        User current = getCurrentUserFromJwt(authHeader);
        if (current == null) {
            return ResponseEntity.status(401).body(Map.of("success", false, "message", "未登录"));
        }
        
        if (!hasUserManagementAccess(current)) {
            return ResponseEntity.status(403).body(Map.of("success", false, "message", "无权限访问"));
        }

        User user = userService.findById(id);
        if (user != null) {
            // 部门管理员只能查看自己可管理部门的用户
            if (isDeptManager(current) && !canManageUser(current, user)) {
                return ResponseEntity.status(403).body(Map.of("success", false, "message", "无权限访问该用户"));
            }

            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("data", user);
            return ResponseEntity.ok(response);
        } else {
            return ResponseEntity.notFound().build();
        }
    }

    @GetMapping("/by-department/{departmentId}")
    public ResponseEntity<?> getUsersByDepartment(@PathVariable Long departmentId,
                                                @RequestHeader(value = "Authorization", required = false) String authHeader) {
        User current = getCurrentUserFromJwt(authHeader);
        if (current == null) {
            return ResponseEntity.status(401).body(Map.of("success", false, "message", "未登录"));
        }
        
        if (!hasUserManagementAccess(current)) {
            return ResponseEntity.status(403).body(Map.of("success", false, "message", "无权限访问"));
        }

        // 部门管理员只能查看自己可管理部门的用户
        if (isDeptManager(current) && !canManageDepartment(current, departmentId)) {
            return ResponseEntity.status(403).body(Map.of("success", false, "message", "无权限访问该部门"));
        }

        List<User> users = userService.findByDepartmentId(departmentId);
        Map<String, Object> response = new HashMap<>();
        response.put("success", true);
        response.put("data", users);
        return ResponseEntity.ok(response);
    }

    @GetMapping("/by-departments")
    public ResponseEntity<?> getUsersByDepartments(@RequestParam String departmentIds,
                                                 @RequestHeader(value = "Authorization", required = false) String authHeader) {
        User current = getCurrentUserFromJwt(authHeader);
        if (current == null) {
            return ResponseEntity.status(401).body(Map.of("success", false, "message", "未登录"));
        }
        
        if (!hasUserManagementAccess(current)) {
            return ResponseEntity.status(403).body(Map.of("success", false, "message", "无权限访问"));
        }

        List<Long> deptIds = new ArrayList<>();
        for (String id : departmentIds.split(",")) {
            try {
                deptIds.add(Long.parseLong(id.trim()));
            } catch (NumberFormatException e) {
                // 忽略无效的ID
            }
        }

        // 部门管理员只能查看自己可管理部门的用户
        if (isDeptManager(current)) {
            List<Long> manageableDeptIds = departmentService.getUserManageableDepartments(current.getId())
                    .stream().map(Department::getId).toList();
            deptIds.retainAll(manageableDeptIds); // 只保留可管理的部门
        }

        List<User> users = userService.findByDepartmentIds(deptIds);
        Map<String, Object> response = new HashMap<>();
        response.put("success", true);
        response.put("data", users);
        return ResponseEntity.ok(response);
    }

    @GetMapping("/by-role/{role}")
    public ResponseEntity<?> getUsersByRole(@PathVariable String role,
                                          @RequestHeader(value = "Authorization", required = false) String authHeader) {
        User current = getCurrentUserFromJwt(authHeader);
        if (current == null) {
            return ResponseEntity.status(401).body(Map.of("success", false, "message", "未登录"));
        }
        
        if (!hasUserManagementAccess(current)) {
            return ResponseEntity.status(403).body(Map.of("success", false, "message", "无权限访问"));
        }

        List<User> users = userService.findByRole(role);
        
        // 部门管理员只能查看自己可管理部门的用户
        if (isDeptManager(current)) {
            List<Long> manageableDeptIds = departmentService.getUserManageableDepartments(current.getId())
                    .stream().map(Department::getId).toList();
            users = users.stream()
                    .filter(user -> manageableDeptIds.contains(user.getDepartmentId()))
                    .toList();
        }

        Map<String, Object> response = new HashMap<>();
        response.put("success", true);
        response.put("data", users);
        return ResponseEntity.ok(response);
    }

    @PostMapping
    public ResponseEntity<?> createUser(@RequestBody User user,
                                      @RequestHeader(value = "Authorization", required = false) String authHeader) {
        User current = getCurrentUserFromJwt(authHeader);
        if (current == null) {
            return ResponseEntity.status(401).body(Map.of("success", false, "message", "未登录"));
        }
        
        if (!hasUserManagementAccess(current)) {
            return ResponseEntity.status(403).body(Map.of("success", false, "message", "无权限操作"));
        }

        // 部门管理员只能创建终端用户
        if (isDeptManager(current) && !"END_USER".equals(user.getRole())) {
            return ResponseEntity.badRequest().body(Map.of("success", false, "message", "部门管理员只能创建终端用户"));
        }

        // 部门管理员只能将用户分配到可管理的部门
        if (isDeptManager(current) && user.getDepartmentId() != null) {
            if (!canManageDepartment(current, user.getDepartmentId())) {
                return ResponseEntity.badRequest().body(Map.of("success", false, "message", "无权限分配到该部门"));
            }
        }

        User savedUser = userService.saveUser(user);
        Map<String, Object> response = new HashMap<>();
        response.put("success", true);
        response.put("message", "用户创建成功");
        response.put("data", savedUser);
        return ResponseEntity.ok(response);
    }

    @PutMapping("/{id}")
    public ResponseEntity<?> updateUser(@PathVariable Long id, @RequestBody User user,
                                      @RequestHeader(value = "Authorization", required = false) String authHeader) {
        User current = getCurrentUserFromJwt(authHeader);
        if (current == null) {
            return ResponseEntity.status(401).body(Map.of("success", false, "message", "未登录"));
        }
        
        // 如果是修改自己的信息
        if (current != null && current.getId().equals(id)) {
            // 只允许修改部分字段
            current.setRealName(user.getRealName());
            current.setEmail(user.getEmail());
            current.setPhone(user.getPhone());
            userService.saveUser(current);
            
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("message", "个人信息更新成功");
            response.put("data", current);
            return ResponseEntity.ok(response);
        }

        // 如果是管理员修改其他用户信息
        if (!hasUserManagementAccess(current)) {
            return ResponseEntity.status(403).body(Map.of("success", false, "message", "无权限操作"));
        }

        User existingUser = userService.findById(id);
        if (existingUser == null) {
            return ResponseEntity.notFound().build();
        }

        // 部门管理员只能修改自己可管理部门的用户
        if (isDeptManager(current) && !canManageUser(current, existingUser)) {
            return ResponseEntity.status(403).body(Map.of("success", false, "message", "无权限修改该用户"));
        }

        // 部门管理员只能修改终端用户
        if (isDeptManager(current) && !"END_USER".equals(existingUser.getRole())) {
            return ResponseEntity.badRequest().body(Map.of("success", false, "message", "部门管理员只能修改终端用户"));
        }

        user.setId(id);
        User updatedUser = userService.saveUser(user);
        
        Map<String, Object> response = new HashMap<>();
        response.put("success", true);
        response.put("message", "用户更新成功");
        response.put("data", updatedUser);
        return ResponseEntity.ok(response);
    }

    @DeleteMapping("/{id}")
    public ResponseEntity<?> deleteUser(@PathVariable Long id,
                                      @RequestHeader(value = "Authorization", required = false) String authHeader) {
        User current = getCurrentUserFromJwt(authHeader);
        if (current == null) {
            return ResponseEntity.status(401).body(Map.of("success", false, "message", "未登录"));
        }
        
        if (!hasUserManagementAccess(current)) {
            return ResponseEntity.status(403).body(Map.of("success", false, "message", "无权限操作"));
        }

        User user = userService.findById(id);
        if (user == null) {
            return ResponseEntity.notFound().build();
        }

        // 不能删除自己
        if (current.getId().equals(id)) {
            return ResponseEntity.badRequest().body(Map.of("success", false, "message", "不能删除自己的账户"));
        }

        // 部门管理员只能删除自己可管理部门的终端用户
        if (isDeptManager(current)) {
            if (!canManageUser(current, user)) {
                return ResponseEntity.status(403).body(Map.of("success", false, "message", "无权限删除该用户"));
            }
            if (!"END_USER".equals(user.getRole())) {
                return ResponseEntity.badRequest().body(Map.of("success", false, "message", "部门管理员只能删除终端用户"));
            }
        }

        userService.deleteUser(id);
        
        Map<String, Object> response = new HashMap<>();
        response.put("success", true);
        response.put("message", "用户删除成功");
        return ResponseEntity.ok(response);
    }

    @PostMapping("/change-password")
    public ResponseEntity<?> changePassword(@RequestBody Map<String, String> params) {
        User user = userService.getCurrentUser();
        if (user == null) {
            return ResponseEntity.status(401).body(Map.of("message", "未登录"));
        }

        String currentPassword = params.get("currentPassword");
        String newPassword = params.get("newPassword");

        if (currentPassword == null || newPassword == null) {
            return ResponseEntity.badRequest().body(Map.of("message", "请提供当前密码和新密码"));
        }

        if (!passwordEncoder.matches(currentPassword, user.getPassword())) {
            return ResponseEntity.badRequest().body(Map.of("message", "当前密码错误"));
        }

        if (newPassword.length() < 6) {
            return ResponseEntity.badRequest().body(Map.of("message", "新密码长度至少6位"));
        }

        user.setPassword(passwordEncoder.encode(newPassword));
        userService.saveUser(user);

        Map<String, Object> response = new HashMap<>();
        response.put("success", true);
        response.put("message", "密码修改成功");
        return ResponseEntity.ok(response);
    }

    // 权限检查方法
    private boolean hasUserManagementAccess(User user) {
        return isAdmin(user) || isDeptManager(user);
    }

    private boolean isAdmin(User user) {
        return user != null && "ADMIN".equals(user.getRole());
    }

    private boolean isDeptManager(User user) {
        return user != null && "DEPT_MANAGER".equals(user.getRole());
    }

    private boolean canManageUser(User current, User target) {
        if (isAdmin(current)) return true;
        if (!isDeptManager(current)) return false;
        
        List<Long> manageableDeptIds = departmentService.getUserManageableDepartments(current.getId())
                .stream().map(Department::getId).toList();
        return manageableDeptIds.contains(target.getDepartmentId());
    }

    private boolean canManageDepartment(User current, Long departmentId) {
        if (isAdmin(current)) return true;
        if (!isDeptManager(current)) return false;
        
        List<Long> manageableDeptIds = departmentService.getUserManageableDepartments(current.getId())
                .stream().map(Department::getId).toList();
        return manageableDeptIds.contains(departmentId);
    }
} 